/**
 * 
 */
package com.sys.console.cookie;

import java.io.IOException;
import java.util.Date;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.ExcessiveAttemptsException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;

import com.sys.console.business.SysUserService;
import com.sys.console.monitor.LoginLogs;
import com.sys.console.pojo.Sys_User;
import com.sys.object.common.context.Config;
import com.sys.object.common.context.ServiceInitContainer;
import com.sys.object.common.utils.DateUtils;
import com.sys.object.common.utils.IpUtils;
import com.sys.object.common.utils.MyStringUtils;

/**
 * @author 张喜朋
 * 
 */
public class LoginFilter implements Filter {
	public final Logger urlLoger = Logger.getLogger("urlLoger");

	@Autowired SysUserService sysUserService;

	@Override
	public void destroy() {
		// TODO Auto-generated method stub
	}

	@Override
	public void doFilter(ServletRequest req, ServletResponse res,FilterChain chain) throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) req;
		HttpServletResponse response = (HttpServletResponse) res;
		String reqUrl = request.getRequestURI();
		Sys_User user = (Sys_User) SecurityUtils.getSubject().getSession().getAttribute(Constant_Cookie.CURRENT_USER_SESSION);
		String company = (String) request.getSession().getAttribute(Constant_Cookie.SESSION_COMPANY);
		if(!StringUtils.hasText(company)){
			 request.getSession().setAttribute(Constant_Cookie.SESSION_COMPANY, MyStringUtils.decodeUnicode(Config.getConfigValue("company")));
		}
		if(user==null){
			user = new Sys_User();
			user.setUid(0);
		}
		urlLoger.info(DateUtils.foramteDate_hh_mm_ss(new Date())+"	"+IpUtils.getIpAddr(request)+"	用户	"+user.getUsername()+"	"+reqUrl);
		if(reqUrl.indexOf(".json")==-1){
			if(reqUrl.indexOf("welcome.do")==-1&&reqUrl.indexOf("meun.do")==-1&&reqUrl.indexOf("index.do")==-1&&reqUrl.indexOf("model.do")==-1&&reqUrl.indexOf("sysUserModuleList.do")==-1&&reqUrl.indexOf("top.do")==-1 && reqUrl.indexOf("usage.do")==-1){
				user.setLtime(new Date());
				user.setLip(IpUtils.getIpAddr(request));
				//MonitorLogs.filterSaveLogs(user.getUid(), 4, null,request);
			}
//			if(user.getUid()==0&&reqUrl.indexOf("login")==-1){
//				request.getRequestDispatcher("/WEB-INF/pages/login.jsp").forward(req, res);
//				//request.getRequestDispatcher("/WEB-INF/h-ui-html/login.jsp").forward(req, res);
//				//request.getRequestDispatcher("/WEB-INF/app/login.html").forward(req, res);
//			}else{
//				chain.doFilter(request, response);
//			}
			chain.doFilter(request, response);
		}else{
			chain.doFilter(request, response);
		}
	}

	@Override
	public void init(FilterConfig config) throws ServletException {
		// TODO Auto-generated method stub
		sysUserService = (SysUserService) ServiceInitContainer.getBean("sysUserService");
		config.getServletContext().setAttribute("servletContext",config.getServletContext());
	}
	
	
	public boolean loginBycookie(Sys_User user,HttpServletRequest request){
		UsernamePasswordToken token = new UsernamePasswordToken(user.getUsername(), user.getPassword());
        if(token==null)
        	return false;
		token.setRememberMe(true);  
        Subject currentUser = SecurityUtils.getSubject();  
		try {  
            currentUser.login(token);  
        }catch(UnknownAccountException uae){  
//            System.out.println("对用户[" + sysUser.getUsername() + "]进行登录验证..验证未通过,未知账户");  
//            //request.setAttribute("message", "未知账户"); 
//            ret.setResultCode(ResultCode.USER_LOGIN_DELETE);
//            model.addAttribute("ret", ret);
//            return "/login";
        }catch(IncorrectCredentialsException ice){  
//            System.out.println("对用户[" + sysUser.getUsername() + "]进行登录验证..验证未通过,错误的凭证");  
//            //request.setAttribute("message", "密码不正确"); 
//            ret.setResultCode(ResultCode.USER_PASSWORD_ERROR);
//            model.addAttribute("ret", ret);
//            return "/login";
        }catch(LockedAccountException lae){  
//            System.out.println("对用户[" + sysUser.getUsername() + "]进行登录验证..验证未通过,账户已锁定");  
//            //request.setAttribute("message", "账户已锁定");  
//            ret.setResultCode(ResultCode.USER_ACCOUNT_LOCKED);
//            model.addAttribute("ret", ret);
//            return "/login";
        }catch(ExcessiveAttemptsException eae){  
//            System.out.println("对用户[" + sysUser.getUsername() + "]进行登录验证..验证未通过,错误次数过多");  
//            //request.setAttribute("message", "用户名或密码错误次数过多");
//            ret.setResultCode(ResultCode.USER_LOGIN_TIMES_ERROR);
//            model.addAttribute("ret", ret);
//            return "/login";
            
        }catch(AuthenticationException ae){  
            //通过处理Shiro的运行时AuthenticationException就可以控制用户登录失败或密码错误时的情景  
//            System.out.println("对用户[" + sysUser.getUsername() + "]进行登录验证..验证未通过,堆栈轨迹如下");  
//            ae.printStackTrace();  
//            //request.setAttribute("message", "用户名或密码不正确");  
//            ret.setResultCode(ResultCode.USER_LOGIN_USERNAME_PASSWORD_ERROR);
//            model.addAttribute("ret", ret);
//            return "/login";
        }  
        //验证是否登录成功  
        if(currentUser.isAuthenticated()){  
            System.out.println("用户[" + user.getUsername() + "]登录认证通过(这里可以进行一些认证通过后的一些系统参数初始化操作)");  
            //更新登陆日志
        	try{
        		//Sys_User User = new Sys_User();
        		Sys_User User = (Sys_User) request.getSession().getAttribute(Constant_Cookie.CURRENT_USER_SESSION);
            	User.setLtime(new Date());
            	User.setLip(IpUtils.getIpAddr(request));
            	sysUserService.updateLoginInfo(User);
            	LoginLogs.monSaveLoginInfo(User,1,request);
        	}catch(Exception e){
        		System.out.println("登录异常");
        	}
        }else{  
            token.clear();  
        }  
        return true;
	}
	

}
